package com.suma.platform.core.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author suma
 * @date 2018/2/6 上午9:53
 */
public class QueueTestThread {

	private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();

	public static void main(String[] args) {
		DoWork dw = new DoWork(map);
		ExecutorService pool = Executors.newFixedThreadPool(8);
		try {
			for (int i = 0; i < 20; i++) {
				pool.execute(new Thread(dw));// 开启20个线程
			}
			Thread.sleep(5000);// 主线程睡眠5s 等待子线程完成任务
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.shutdown();// 关闭线程池
		}
		System.out.println("统计的数量：" + map.get("count"));
	}

	static class DoWork implements Runnable {

		private ConcurrentHashMap<String, Integer> map = null;

		public DoWork(ConcurrentHashMap<String, Integer> map) {
			this.map = map;
		}

		@Override
		public void run() {
			add("count");
		}

		synchronized public void add(String key) {
			Integer value = map.get(key);// 获取map中的数值
			System.out.println("当前数量" + value);
			if (null == value) {
				map.put(key, 1);// 第一次存放
			} else {
				map.put(key, value + 1);// 以后次存放
			}
		}

	}

}
